package service

import (
	"api/internal/svc"
	"context"
	"encoding/json"
	"fmt"
	"github.com/gomodule/redigo/redis"
	"strconv"
)

// 扫码点餐服务
type OrderFoodService struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewOrderFoodService(ctx context.Context, svcCtx *svc.ServiceContext) *OrderFoodService {
	return &OrderFoodService{
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

var (
	ORDER_FOOD_GOODS = "order_food:goods:" // :前面的是模块
)

type OrderFoodGoods struct {
	Id             int64  `json:"id"`
	Title          string `json:"title"`
	Price          int64  `json:"price"`
	Img            string `json:"img"`
	Specifications string `json:"specifications"`
	Properties     string `json:"properties"`
	Jialiao        string `json:"jialiao"`
	Des            string `json:"des"`
}

// 获取商品列表
// busId: 商家id  categoryId:分类id
func (orderFoodService *OrderFoodService) GetGoodsList(redis redis.Conn, busId int64, categoryId int64) (*[]OrderFoodGoods, error) {
	// 获取商品主体
	key := ORDER_FOOD_GOODS + strconv.Itoa(int(busId)) + ":" + strconv.Itoa(int(categoryId)) // 商家id:分类id
	ret, _ := redis.Do("HVALS", key)

	if ret == nil {
		return nil, nil
	}
	slice := ret.([]interface{})

	resp := make([]OrderFoodGoods, len(slice))
	var goods OrderFoodGoods
	for index, item := range slice {
		json.Unmarshal(item.([]byte), &goods)
		resp[index] = goods
	}

	return &resp, nil
}

// 删除分类下的所有商品
// busId: 商家id  categoryId:分类id
func (orderFoodService *OrderFoodService) DelGoodsList(redis redis.Conn, busId int64, categoryId int64) {
	// 获取商品主体
	key := ORDER_FOOD_GOODS + strconv.Itoa(int(busId)) + ":" + strconv.Itoa(int(categoryId)) // 商家id:分类id
	_, err := redis.Do("DEL", key)
	if err != nil {
		fmt.Println(err.Error())
	}
}

// 保存商品(上架)
// busId: 商家id  categoryId:分类id
func (orderFoodService *OrderFoodService) SaveGoods(redis redis.Conn, busId int64, categoryId int64, goods *OrderFoodGoods) {
	key := ORDER_FOOD_GOODS + strconv.Itoa(int(busId)) + ":" + strconv.Itoa(int(categoryId)) // 商家id:分类id
	jsonD, _ := json.Marshal(goods)
	redis.Do("HSET", key, goods.Id, jsonD)
}

// 删除商品
// busId: 商家id  categoryId:分类id
func (orderFoodService *OrderFoodService) DelGoods(redis redis.Conn, busId int64, categoryId int64, id int64) {
	key := ORDER_FOOD_GOODS + strconv.Itoa(int(busId)) + ":" + strconv.Itoa(int(categoryId)) // 商家id:分类id
	redis.Do("HDEL", key, id)
}
